package com.jessechanrui.template.common.template.auth.websocket;
import org.springframework.web.reactive.socket.WebSocketHandler;
import org.springframework.web.reactive.socket.WebSocketSession;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.Duration;

/**
 * @author chenrui
 * @version 1.0
 * @description StreamingWebSocketHandler
 * @date 2025/8/12
 */
public class StreamingWebSocketHandler implements WebSocketHandler {

    @Override
    public Mono<Void> handle(WebSocketSession session) {
        // 1. 创建流式数据源（每秒发送一次）
        Flux<String> stream = Flux.interval(Duration.ofSeconds(1))
                .map(i -> "WebFlux 流式数据: " + i)
                .doOnNext(data -> System.out.println("发送: " + data));

        // 2. 将数据流写入 WebSocket
        return session.send(
                stream.map(session::textMessage) // 转换为 WebSocket 消息
        ).and(
                session.receive() // 可选：处理客户端消息
                        .doOnNext(message -> System.out.println("收到客户端: " + message.getPayloadAsText()))
        );
    }
}
